﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Globalization;
using FreeImageAPI;
using FreeImageAPI.Metadata;
using ArgusPCLib.Collections;
using System.Xml;
using System.Xml.Linq;

namespace Imagenator
{
	class ImageInfo
	{
		public DateTime Timestamp { get; private set; }
		public int Number { get; private set; }
		public string Filename { get; private set; }
		static readonly ListPair<string, string> tagsDate = new ListPair<string,string>(
			new string[]{"DateTimeOriginal",	"CreateDate",	"Creation Time",	"date created",	"DateTime",				"tIme"},
			new string[]{"yyyy:MM:dd HH:mm:ss",	null,			null,				null,			"yyyy:MM:dd HH:mm:ss",	null});

		public ImageInfo(DateTime timestamp, int number, string filename)
		{
			this.Timestamp = timestamp;
			this.Number = number;
			this.Filename = filename;
		}

		public static ImageInfo GetInfo(string path, int number)
		{
			FREE_IMAGE_FORMAT fif = FreeImage.GetFIFFromFilename(path);
			FREE_IMAGE_LOAD_FLAGS flags = FREE_IMAGE_LOAD_FLAGS.DEFAULT;
			if (FreeImage.FIFSupportsNoPixels(fif))
				flags |= FREE_IMAGE_LOAD_FLAGS.FIF_LOAD_NOPIXELS;

			using (FreeImageBitmap image = new FreeImageBitmap(path, flags))
			{
				return ImageInfo.GetInfo(image, number, path);
			}
		}

		public static ImageInfo GetInfo(FreeImageBitmap image, int number, string path)
		{
			WICMetadataHandler meta = image.GetWICMetadataHandler();
			DateTime dateTaken;
			if (meta.DateTaken.HasValue)
			{
				dateTaken = meta.DateTaken.Value;
			}
			else
			{
				DateTime fileTime = File.GetCreationTime(path);
				MDM_EXIF_MAIN mModel = (MDM_EXIF_MAIN)image.Metadata[FREE_IMAGE_MDMODEL.FIMD_EXIF_MAIN];
				MetadataTag tag = mModel.GetTag("DateTime");
				string val = tag.Value.ToString();
				DateTime dt;
				if (!DateTime.TryParseExact(val, "yyyy:MM:dd HH:mm:ss\0", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out dt))
					dt = DateTime.Now;
				if (dt < fileTime)
					dateTaken = dt;
				else
					dateTaken = fileTime;
				meta.DateTaken = dateTaken;
				meta.Save();
			}

			return new ImageInfo(dateTaken, number, path);
		}
	}
}
